package com.sunrise.gateway;

import com.alibaba.fastjson.JSON;
import com.dap.exception.BusinessException;
import com.dap.param.StringInput;
import com.sunrise.gateway.commons.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangmin
 * @discription
 * @created 2020-04-29 13:54
 */
public abstract class FrontendVersionManagerBase {
    private final static Logger logger = LoggerFactory.getLogger(FrontendVersionManagerBase.class);
    protected static final Map<String, String> versionMap = new ConcurrentHashMap<>();


    public static String getFrontendVersion(String host) {
        return versionMap.get(host);
    }
    public static void updateFrontendVersion(String host, String version) {
        versionMap.put(host, version);
    }

    public static void printFrontendVersion() {
        logger.info("FrontendVersion={}", JSON.toJSONString(versionMap));
    }

    public static void checkFrontendVersion(HttpServletRequest req, StringInput stringInput) {
        // 获取域名
        final String host = req.getHeader("host");
        if (StringUtils.isEmpty(host)) {
            return;
        }

        String frontendVersion = stringInput.getCtrlData().getFrontendVersion();
        if (StringUtils.isEmpty(frontendVersion)) {
            return;
        }

        if (!frontendVersion.equals(versionMap.get(host))) {
            throw new BusinessException(Constants.FRONTEND_VERSION_UPDATED);
        }
    }
}
